import { ErrorTypes, handleError, withRetry } from '@/utils/errorHandler';

const HISTORY_BASE_API = 'https://hot.cigh.cn';

// 获取历史上的今天
export const getHistoryToday = async () => {
    try {
        const today = new Date();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        console.log(month, day, 'month, day');
        const response = await withRetry(() =>
            uni.request({
                url: `${HISTORY_BASE_API}/calendar/date`,
                method: 'GET',
                data: { month, day },
            })
        );
        // 检查响应状态
        if (!response.data || response.data.code !== 200) {
            throw new Error(
                response.data?.message || '获取历史上的今天数据失败'
            );
        }

        return response.data;
    } catch (error) {
        handleError(error, ErrorTypes.API);
        throw error;
    }
};

// 获取指定平台的热搜数据
export const getHotSearch = async (platform) => {
    try {
        const response = await withRetry(() =>
            uni.request({
                url: `${HISTORY_BASE_API}/${platform}`,
                method: 'GET'
            })
        );

        if (!response.data || response.data.code !== 200) {
            throw new Error(
                response.data?.message || `获取${platform}热搜数据失败`
            );
        }

        return response.data;
    } catch (error) {
        handleError(error, ErrorTypes.API);
        throw error;
    }
};

// 获取所有支持的平台列表
export const getSupportedPlatforms = async () => {
    try {
        const response = await withRetry(() =>
            uni.request({
                url: `${HISTORY_BASE_API}/all`,
                method: 'GET'
            })
        );

        if (!response.data || response.data.code !== 200) {
            throw new Error(
                response.data?.message || '获取支持的平台列表失败'
            );
        }

        return response.data;
    } catch (error) {
        handleError(error, ErrorTypes.API);
        throw error;
    }
};
